package common.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class FHEncrypt {
	private static Key key;
	public static void GenKey() throws NoSuchAlgorithmException, FileNotFoundException, IOException{
		
	}
	public static void getKey(String password){ 
		String KeyStr="9Bw0dk3ick]0`dj_";
		byte[] b = KeyStr.getBytes();
        SecretKeySpec spec = new SecretKeySpec(b,"AES");
        key = spec;
	}
	public static String encrypt(String src){
		SecureRandom sr = new SecureRandom();
         try{
        	 Cipher cipher = Cipher.getInstance("AES");
        	 cipher.init(Cipher.ENCRYPT_MODE, key);
        	 byte[] b=cipher.doFinal(src.getBytes());
        	 return new String(b);
         }catch(Exception e){
        	 
         }
		return null;
	}
	public static byte[] encrypt(byte[] src,int mode){
	
		SecureRandom sr = new SecureRandom();
        try{
	       	
        	Cipher cipher = Cipher.getInstance("AES");
        	cipher.init(mode, key);
	       	System.out.println(key.getEncoded());
        	int blockSize = cipher.getBlockSize();
	       	
	       	int slen = src.length;
	       	byte[] b=new byte[blockSize];
	       	int x = slen/blockSize;
	       	int y = slen%blockSize;
	       	String rst="";
	       	int i;
	       	byte[] r=new byte[(x+1)*blockSize];
	       	for(i=0;i<x;i++){
	       		cipher.update(src, i*blockSize, blockSize,b);
	       		for(int j=0;j<b.length;j++)
	       			r[j+i*blockSize]=b[j];
	       	}
	       	if(y>0)
	       		cipher.doFinal(src, i*blockSize, y,b);
	       	else
	       		b=cipher.doFinal();
	       	for(int j=0;j<b.length;j++)
       			r[j+i*blockSize]=b[j];
        	//IvParameterSpec spec=new IvParameterSpec(key.getEncoded());
	        //cipher.init(mode, key,spec,sr);
       	    
       	    
	       	return r;
        }catch(Exception e){
       	 	e.printStackTrace();
        }
		return null;
	}
}
